<?php

require_once(APP.'libs'.DS.'system_properties.php');
require_once(APP.'libs'.DS.'my_app_model.php');

App::import('Vendor','/infolex/app_config');
class User extends MyAppModel
{
	var $name='User';
	var $validate = array();

	//用户填写信息
	function saveUserInfo($g_id,$_POST){
		//$sex = mysql_escape_string($_POST['sex']);
		$realname = mysql_escape_string($_POST['realname']);
		//$birthday = mysql_escape_string($_POST['birthday']);
		$phone = mysql_escape_string($_POST['phone']);
		$mail = mysql_escape_string($_POST['mail']);
		//$city = mysql_escape_string($_POST['city']);
		$address = mysql_escape_string($_POST['address']);
		$idcard = mysql_escape_string($_POST['idcard']);
		$zipcode = mysql_escape_string($_POST['zipcode']);
		//$interest = mysql_escape_string($_POST['interest']);
		//$kuaidi = mysql_escape_string($_POST['kuaidi']);

		$sql="update g_users set `g_realname`='$realname',`g_phone`='$phone',`g_mail`='$mail',`g_address`='$address',`g_zipcode`='$zipcode',`g_idcard`='$idcard' where g_id=$g_id ";
		return $this->query($sql);
	}
	//save invite log
	function saveInviteLog($from,$to){
		$to = intval($to);
		$from = intval($from);
		$sql = "select `from` from g_invitelogs where `to`={$to} limit 1";
		$data = $this->query($sql);
		if (empty($data[0]['g_invitelogs']['from'])){
			$sql = "insert into g_invitelogs (`from`,`to`)values($from,$to);";
			$data = $this->query($sql);
			return ;

		}else {
			//只记录第一个邀请的用户。
			//$sql = "update g_invitelogs set `from`=$from where `to`=$to";
			//$data = $this->query($sql);
			return ;
		}

	}
	function getIP(){
	    $user_IP = ($_SERVER["HTTP_VIA"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : $_SERVER["REMOTE_ADDR"];
		$user_IP = ($user_IP) ? $user_IP : $_SERVER["REMOTE_ADDR"];
		return $user_IP;
	}
	function UpdateUserIP($id) {
	    $user_IP = !empty($_SERVER["HTTP_VIA"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : $_SERVER["REMOTE_ADDR"];
		$user_IP = !empty($user_IP) ? $user_IP : $_SERVER["REMOTE_ADDR"];
		
		$id = intval($id);
		$user_IP = mysql_escape_string($user_IP);
		$sql = "UPDATE `g_users` SET `g_ip` = '$user_IP' WHERE g_id ={$id}";
		return $this->query($sql);

	}	
	
	//获取领取剩余次数
	function getApplyCountLeft($uid){
	    $uid = intval($uid);
	    $data = $this->getUserInfoById($uid);
	    
	    if (empty($data['g_canapply'])) {
	        return 0;
	    } else {
	        return $data['g_canapply'];
	    }

	}
	//检查今天是否已经领取
	function checkApplyTodayCount($user_id){
	    $user_id = intval($user_id);
		$data = $this->query("select count(1) as n from  g_timesplit_logs where user_id=$user_id and TO_DAYS(time)=TO_DAYS(now())");
		return $data[0][0]['n'];
	}	

	//检查今天是否已经领取
	function checkIsApplyedToday($user_id,$id){
	    $user_id = intval($user_id);
	    $id = intval($id);
		$data = $this->query("select count(1) as n from  g_timesplit_logs where user_id=$user_id and product_id=$id and TO_DAYS(time)=TO_DAYS(now())");
		if (empty($data[0][0]['n'])){
			return 0;
		}else {
			return 1;
		}
	}
	//检查
	function checkInviteRewardToday($user_id){
		$data = $this->query("select count(1) as n from g_invitelogs where `from`={$user_id} and `reward`=1 and TO_DAYS(g_time)=TO_DAYS(now()) limit 1");
		if (empty($data[0][0]['n'])){
			return 0;
		}else {
			return $data[0][0]['n'];
		}
	}	//
	
	function checkInviteRewardAll($user_id){
		$data = $this->query("select count(1) as n from g_invitelogs where `from`={$user_id} and `reward`=1 limit 1");
		if (empty($data[0][0]['n'])){
			return 0;
		}else {
			return $data[0][0]['n'];
		}
	}
	
	
	//保存申请记录 //两份一份是用户的记录 一份是用来计算抽奖以及列出信息的记录表
	
	function addShowCount($id){
		$id = intval($id);
		$this->query("update g_products set clickcount=clickcount+1,popularity=popularity+1 where g_id=$id");
	}

	function getUserInfoByPlatformId($id){
		$data = $this->query("select * from g_users u where g_uid={$id} limit 1 #".microtime(1).rand(0,10000000000));
		if (empty($data)) {
		    return array();
		} else {
		    $data = $data[0]['u'];
		    $data['level'] = SystemProperties::getUserLevelInfo($data);
		    return $data;
		}
	}
	function getUserInfoById($g_id){
		$g_id = intval($g_id);
		$data = $this->query("select * from g_users u where g_id={$g_id} limit 1");
		if (empty($data)) {
		    return array();
		} else {
		    $data = $data[0]['u'];
		    $data['level'] = SystemProperties::getUserLevelInfo($data);
		    return $data;
		}
	}
	function getUserIdByPlatformUId($g_id){
		$g_id = intval($g_id);
		$data = $this->query("select g_id from g_users u where g_uid={$g_id} limit 1");
		if (empty($data[0]['u']['g_id'])){
			return 0;
		}else {
			return $data[0]['u']['g_id'];
		}
		return $data;
	}
	

	function updateUserDate($g_id, $userInfo, $user_data_in_db){
	    if (!empty($user_data_in_db) && (date('Y-m-d',strtotime($user_data_in_db['g_login_time'])) != date('Y-m-d'))) {
    	    $level = SystemProperties::getUserLevelInfo($user_data_in_db);
    	    $addApply = intval($level['apply']);	        
    		$sql="update g_users set `g_canapply`=`g_canapply`+$addApply,`g_active_day`=`g_active_day`+1 where g_id=$g_id and TO_DAYS(g_login_time)<>TO_DAYS(now())";
    		$this->query($sql);
	    }

		if (!empty($userInfo['user']['name'])){
			if(empty($userInfo['user']['name'])){
				$name="匿名";
			}else{
				$name=$userInfo['user']['name'];
			}
			if(empty($userInfo['user']['headurl'])){

				if (empty($userInfo['user']['pic'])){
					$head="http://www.xiaonei.com";
				}else {
					$head=$userInfo['user']['pic'];
				}
			}else{
				$head=$userInfo['user']['headurl'];
			}
			if(empty($userInfo['user']['sex'])){
				$sex=0;
			}else{
				$sex=$userInfo['user']['sex'];
			}
			$name = mysql_escape_string($name);
			$head = mysql_escape_string($head);
			$sex = intval($sex);
			$g_id = intval($g_id);
			$sql="update g_users set g_login_time=now(),g_name='{$name}',g_head='{$head}',g_sex='{$sex}' where g_id={$g_id}";
			$this->query($sql);
		}else {
			$sql="update g_users set g_login_time=now() where g_id=$g_id";
			$this->query($sql);
		}

	}

	function createUser($userInfo,$friends=array('uid'=>array())){
        //		$sql="SELECT now() ";
        //		$data=$this->query($sql);
        //		$time=$data[0][0]['now()'];
		//本机时间相同
		
        $time = date('Y-m-d H:i:s');
		if(empty($userInfo['user']['name'])){
			$name="匿名";
		}else{
			$name=$userInfo['user']['name'];
		}
		if(empty($userInfo['user']['headurl'])){

			if (empty($userInfo['user']['pic'])){
				$head="http://www.xiaonei.com";
			}else {
				$head=$userInfo['user']['pic'];
			}
		}else{
			$head=$userInfo['user']['headurl'];
		}
		if(empty($userInfo['user']['sex'])){
			$sex=0;
		}else{
			$sex=$userInfo['user']['sex'];
		}
		$userData=array(
		"g_uid"=>$userInfo['user']['uid'],
		"g_name"=>$name,
		"g_money"=>AppConfig::INIT_MONEY,
		"g_head"=>$head,
		"g_sex"=>$sex,
		"g_birthday"=>empty($userInfo['user']['birthday'])?'':$userInfo['user']['birthday'],
		"g_country"=>"中国",
		"g_province"=>empty($userInfo['user']['hometown_location']['province'])?'':$userInfo['user']['hometown_location']['province'],
		"g_city"=>empty($userInfo['user']['hometown_location']['city'])?'':$userInfo['user']['hometown_location']['city'],
		"g_add_time"=>$time,
		"g_message"=>$time,
		"g_status"=>1,
		"g_friends"=>''
		);
		$user= $this->save($userData);
		
		// 站内邀请的奖励
		$sql = "select `from` from g_invitelogs where `to`={$userInfo['user']['uid']} and `reward`=0 order by seqid desc limit 1";
		$data = $this->query($sql);
		if (empty($data[0]['g_invitelogs']['from'])){

		}else {
			
			$fromid = intval($data[0]['g_invitelogs']['from']);
			$sql = "update g_invitelogs set `reward`=1 where `to`={$userInfo['user']['uid']} and `from`={$fromid}";
			$this->query($sql);
			
			$sql = "select `g_gold_invite_count` from g_users where `g_uid`='{$fromid}'";
			$datax = $this->query($sql);
			$gold_add = 0;
			//每5个加一个。
			if (!empty($datax[0]['g_users']['g_gold_invite_count'])){
			    if ($datax[0]['g_users']['g_gold_invite_count'] % 5 == 4) {
			        $gold_add = 1;
			    } 
			}
			
            $sql = "update g_users set `g_gold_invite_count`=`g_gold_invite_count`+1,`g_gold`=`g_gold`+$gold_add where `g_uid`='{$fromid}'";
			$this->query($sql);
			
			//只有金币奖励
			
            //			if ($this->checkInviteRewardAll($fromid)>30 || $this->checkInviteRewardToday($fromid)>5){
            //				//累计最多30个
            //				//每日最多5个
            //				
            //				
            //			}else {
            //				$sql = "update g_users set `g_canapply`=`g_canapply`+1,`g_money`=`g_money`+1 where `g_uid`='{$fromid}'";
            //				$this->query($sql);
            //			}

		}
		//$user_id=$this->id;
		return $user;
	}
	
	function getRecentApply($n){
		
		$n = intval($n);
		
		$key = 'getRecentApply_'.$n;
		if ($ret = Cache::read($key, 'short_time')) {
		    return $ret;
		}
		
		$sql = "SELECT g_timesplit_logs.*,g_users.g_name,g_users.g_head,g_users.g_uid,g_products.g_name as g_product,product_id as pid  FROM `g_timesplit_logs` left join g_users on g_users.g_id=g_timesplit_logs.user_id  left join g_products on g_products.g_id=g_timesplit_logs.product_id  WHERE 1 order by g_timesplit_logs.seqid desc limit $n";
		$data = $this->query($sql);
		if (!empty($data)){
			$ret = array();
			foreach ($data as $da){
				$ret[] = array_merge($da['g_timesplit_logs'],$da['g_users'],$da['g_products']);
			}
			Cache::write($key, $ret, 'short_time');
			return $ret;			
		}else {
			return array();
		}
	}
	function saveCutePigLog($uid, $type='pig'){
		if (empty($uid)) {
			error_log('call add saveCutePigLog with session['.json_encode($_SESSION).'] server['.json_encode($_SERVER).']');
		}
	    $time = (date('Y-m-d'));
	    $time_r = (date('Y-m-d H:i:s'));
	    $uid = intval($uid);
	    $sql = "INSERT INTO `cutepig_user_log` (`time` ,`uid`, `type`, `r_time`)VALUES ('{$time}' , '{$uid}', '{$type}', '{$time_r}');";
	    $data = $this->query($sql);

	}
	
	function saveViewLog($user_id,$product_id){
		if (empty($user_id)) {
			return ;
		}
		$user_id = intval($user_id);
		$product_id = intval($product_id);
		$sql = "insert into  g_viewlogs (user_id,product_id)values({$user_id},{$product_id})";
		$data = $this->query($sql);
	}
	
	function getConfig($key){
		$key =mysql_escape_string($key);
//		if ($ret = Cache::read($key)) {
//		    return $ret;
//		}
		
		$sql = "select `value` from  `g_config` where `key` = '$key' ";
		$data = $this->query($sql);
		if (!empty($data[0]['g_config']['value'])){
			$ret = $data[0]['g_config']['value'];
//			Cache::write($key, $ret);
			return $ret;
		}else {
			return '';
		}
	}		
	function check_is_in_blacklist($uid) {
	    $blacklist_ids = $this->getConfig('blacklist_ids');
		$t = preg_match_all('/([0-9]+)/', $blacklist_ids, $ma);
		
		if (!empty($ma[1]) && in_array($uid, $ma[1])){
		    return true;
		}
		

		return false;
	}	
	
	function select_invite_friends($uid) {
	    $uid = intval($uid);
	    $sql = "SELECT g_users.g_uid,g_users.`g_head`, g_users.g_name FROM  g_invitelogs  left join  `g_users` on `g_users`.`g_uid` = g_invitelogs.to where g_invitelogs.from={$uid} and  g_invitelogs.reward =1";
	    $data = $this->query($sql);
	    $ret = array();
	    if (empty($data)) {
	        return array();
	    }
	    foreach ($data as $da) {
	        $ret[] = $da['g_users'];
	    }
	    return $ret;
	}

}
